package kr.hkit.android_bookmgr.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.DTO.BookData;
import kr.hkit.android_bookmgr.DTO.FinishedBook;
import kr.hkit.android_bookmgr.activity.AddBookDirectlyActivity;
import kr.hkit.android_bookmgr.adapter.MainListAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class BookListActivity extends Activity {
	
	private BookDAO mBookMgr;
	private String mName, mAuthor, mPublisher, mBookimg, mStartdate, mEnddate;
	private int mImgtype, mTotalpage, mCurrentpage, mStatus, mId, searchId;
	private ArrayList<BookData> arItems;
	private GridView grid;
	private int pos;
	private MainListAdapter adapter;
	private Boolean is_finish = false; //종료시
	private ArrayList<FinishedBook> finishedBooks;
	private int thisMonth;
	private TextView statistic;
	private int mDay;
	private boolean flag = true;
	public int goalNum;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("TEST", "LISTMAIN - onCreate");

		setContentView(R.layout.booklist_activity);
		
		mBookMgr = BookDAO.getInstance(this);
		
		Calendar cal = new GregorianCalendar();
		int mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH); //목표받기용
		thisMonth = mMonth + 1; // 이번달은 몇월인지

		SharedPreferences pref = getSharedPreferences("PrefGoal", Activity.MODE_PRIVATE);
		goalNum = pref.getInt("goalNum", 0);
		
		statistic = (TextView) findViewById(R.id.booklist_finishbook);
		finishedBooks = mBookMgr.selectStatistic();
		for (int i = 0; i < finishedBooks.size(); i++) {
			if (finishedBooks.get(i).month == thisMonth) {
				statistic.setText(thisMonth+"월 : " + finishedBooks.get(i).count+"/" + goalNum + "권 (달성/목표)");
			}
		}
		
		Spinner spin = (Spinner) findViewById(R.id.booklist_status);
		spin.setPrompt("상태를 고르세요");
		
		final ArrayAdapter<CharSequence> adspin = ArrayAdapter.createFromResource(this, R.array.booklist_statuslist, android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adspin);
	
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				
				switch(position){
				case 0: // 전체
					arItems = mBookMgr.selectListMain();
					adapter = new MainListAdapter(BookListActivity.this,arItems);
					grid.setAdapter(adapter);
					break;
				case 1: //읽을예정 status 1						
				case 2: //status 2				
				case 3: //status 3
					arItems = mBookMgr.selectListMainSpinner(position);
					adapter = new MainListAdapter(BookListActivity.this, arItems);
					grid.setAdapter(adapter);
					break;
				}
			} //상태 스피너.

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		
		
		//ListBaseAdapter 이건 첫 메인 리스트 
		mBookMgr = new BookDAO(this);
		arItems = mBookMgr.selectListMain();

		grid = (GridView) findViewById(R.id.booklist_grid);
		//그냥클릭 - 책갈피 용
		grid.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				
				pos = position;
				searchId = arItems.get(position).id;
				Cursor c = mBookMgr.selectGridItem(searchId);
				//Toast.makeText(getApplicationContext(), searchId+"", Toast.LENGTH_SHORT).show();
				
				cursorStart(c);
				
				BookData book = new BookData(searchId, mName, mAuthor, mPublisher, mBookimg, mImgtype, mStatus, mTotalpage, mCurrentpage, mStartdate, mEnddate);
				Intent intent = new Intent(BookListActivity.this, BookMarkActivity.class);
				intent.putExtra("BOOK", book);
				startActivity(intent);
				
				
			}
		});
		
		
		//롱클릭 - 수정삭제
		grid.setOnItemLongClickListener(new OnItemLongClickListener() { 
			private int longPos;
			private int longClicksearchId;
			
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				longPos = position;
				
				new AlertDialog.Builder(BookListActivity.this).
				setTitle("원하는 항목을 선택하십시오.").
				setItems(R.array.booklist_updel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						String[] pickimg = getResources().getStringArray(R.array.booklist_updel);
						if(which==0){ //수정
							
							//Toast.makeText(getApplicationContext(), "searchId: " + searchId + " 롱클릭은?: " +longClicksearchId, Toast.LENGTH_SHORT).show();
							
							longClicksearchId = arItems.get(longPos).id; 
							Cursor c = mBookMgr.selectGridItem(longClicksearchId);
							
							cursorStart(c);
							
							BookData book = new BookData(longClicksearchId, mName, mAuthor, mPublisher, mBookimg, mImgtype, mStatus, mTotalpage, mCurrentpage, mStartdate, mEnddate);
							Intent intent = new Intent(BookListActivity.this, BookMarkEditActivity.class);
							intent.putExtra("BOOK", book);
							startActivity(intent);
							
							Toast.makeText(getBaseContext(), pickimg[which]+"을 선택하셨습니다.", Toast.LENGTH_SHORT).show();
							
						}else{ // 삭제 확인창 띄우기 
							
							new AlertDialog.Builder(BookListActivity.this)
							.setTitle("삭제")
							.setMessage("해당 메모도 같이 삭제됩니다. \n 삭제하시겠습니까?")
							.setPositiveButton("확인", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) { //등록버튼 클릭시 -> DB인서트
									//booklist삭제
									String whereClause_book = "_id=?";
									String[] whereArgs_book = new String[1];
									whereArgs_book[0]=Integer.toString(arItems.get(longPos).id);
									mBookMgr.deleteBook(whereClause_book, whereArgs_book);
									
									//memolist삭제
									String whereClause_Memo= "bookid=?";
									String[] whereArgs_Memo = new String[1];
									whereArgs_Memo[0]=Integer.toString(arItems.get(longPos).id);
									mBookMgr.deleteMemo(whereClause_Memo, whereArgs_Memo);
									Toast.makeText(getBaseContext(),"삭제 되었습니다.", Toast.LENGTH_SHORT).show();
									
									//삭제 후 리스트 재호출 
									SharedPreferences pref = getSharedPreferences("PrefGoal", 0);
									int goalNum = pref.getInt("goalNum", 0);
									
									finishedBooks = mBookMgr.selectStatistic();
									for (int i = 0; i < finishedBooks.size(); i++) {
										if (finishedBooks.get(i).month == thisMonth) {
											//statistic.setText(thisMonth+"월 : " + finishedBooks.get(i).count+"권 독서완료!");
											statistic.setText(thisMonth+"월 : " + finishedBooks.get(i).count+"/" + goalNum + "권 (달성/목표)");
										}
									}
									
									arItems = mBookMgr.selectListMain();
									adapter = new MainListAdapter(BookListActivity.this, arItems);
									grid.setAdapter(adapter);
									
								}
							})
							.setNegativeButton("취소", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									Toast.makeText(getBaseContext(),"취소하였습니다.", Toast.LENGTH_SHORT).show();
								}
							})
							.show();
							//삭제확인 AlertDialog
						}//if~else
					}//onClick 수정, 삭제 대화상자
				})
				.setNegativeButton("취소", null)
				.show();
				return true;
			}//onItemLongClick
			
		});//setOnItemLongClickListener

	    adapter = new MainListAdapter(BookListActivity.this, arItems);
		grid.setAdapter(adapter);
		
	}//onCreate
	
	
	protected void cursorStart(Cursor c){
		
		startManagingCursor(c);
		while (c.moveToNext()) {
			mId = c.getInt(c.getColumnIndex("_id")); //
			mName = c.getString(c.getColumnIndex("name"));
			mAuthor = c.getString(c.getColumnIndex("author"));
			mPublisher = c.getString(c.getColumnIndex("publisher"));
			mBookimg = c.getString(c.getColumnIndex("bookimg"));
			mImgtype = c.getInt(c.getColumnIndex("imgtype"));
			mStatus = c.getInt(c.getColumnIndex("status"));
			mTotalpage = c.getInt(c.getColumnIndex("totalpage"));
			mCurrentpage = c.getInt(c.getColumnIndex("currentpage"));
			mStartdate = c.getString(c.getColumnIndex("startdate"));
			mEnddate = c.getString(c.getColumnIndex("enddate"));
			
		}
	}
	
	
	
	@Override
	protected void onRestart() {
		super.onRestart();
		Log.d("TEST", "LISTMAIN - onRestart");
		
		SharedPreferences pref = getSharedPreferences("PrefGoal", 0);
		int goalNum = pref.getInt("goalNum", 0);
		
		finishedBooks = mBookMgr.selectStatistic();
		for (int i = 0; i < finishedBooks.size(); i++) {
			if (finishedBooks.get(i).month == thisMonth) {
				statistic.setText(thisMonth+"월 : " + finishedBooks.get(i).count+"/" + goalNum + "권 (달성/목표)");
			}
		}
		
		mBookMgr = new BookDAO(this);
		arItems = mBookMgr.selectListMain();
		adapter = new MainListAdapter(BookListActivity.this, arItems);
		grid.setAdapter(adapter);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.booklist_actionbarmenu, menu);
		return super.onCreateOptionsMenu(menu);
		
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null ;
	
		switch(item.getItemId()){
		case R.id.booknamesearch_icon: //눌렀을때
			
			LinearLayout ln = (LinearLayout) findViewById(R.id.booklist_upsearchrelative);
			if(flag){
				ln.setVisibility(LinearLayout.VISIBLE);
			}else{
				ln.setVisibility(LinearLayout.GONE);
			}
			
			flag = !flag;
			
			break;
		case R.id.board_icon: //게시판
			intent = new Intent(BookListActivity.this, BookBoardActivity.class);
			startActivity(intent);
			break;
		case R.id.addbook_direct: //도서직접등록
			intent = new Intent(BookListActivity.this, AddBookDirectlyActivity.class);
			startActivity(intent);
			break;
		case R.id.addbook_search: //도서검색
			intent = new Intent(BookListActivity.this, AddBookSearchActivity.class);
			startActivity(intent);
			break;
		
		}
		return super.onOptionsItemSelected(item);
	}//onOptionsItemSelected
	
	 public void mOnClick(View v){
	    	switch(v.getId()){
	    	case R.id.booklist_goal:
	    		if(mDay==22){ //1일이면 목표받기
	    			
	    			final LinearLayout linear = (LinearLayout) View.inflate(BookListActivity.this, R.layout.booklist_goal_dialog, null);
	    			final EditText goal = (EditText) linear.findViewById(R.id.booklist_goal_edittext);
	    			
	    			new AlertDialog.Builder(BookListActivity.this)
	    			.setView(linear)
					.setTitle("목표 등록")
					.setMessage("이번 달 목표 독서량을 입력해 주십시오.")
					.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) { //등록버튼 클릭시 -> DB인서트
							SharedPreferences pref = getSharedPreferences("PrefGoal", 0);
							SharedPreferences.Editor edit = pref.edit();
							int goalNum = Integer.parseInt(goal.getText().toString());
							edit.putInt("goalNum", goalNum);
							edit.commit();
							
							//대화상자 꺼지면서 바로 표시되게 
							int goalNum2 = pref.getInt("goalNum", 0);
							finishedBooks = mBookMgr.selectStatistic();
							for (int i = 0; i < finishedBooks.size(); i++) {
								if (finishedBooks.get(i).month == thisMonth) {
									statistic.setText(thisMonth+"월 : " + finishedBooks.get(i).count+"/" + goalNum2 + "권 (달성/목표)");
								}
							}
							
						}
					})
					.setNegativeButton("취소", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							Toast.makeText(getBaseContext(),"취소하였습니다.", Toast.LENGTH_SHORT).show();
						}
					})
					.show();
	    			
	    		}else{
	    			Toast.makeText(getApplicationContext(), "매월 1일에 목표 등록 가능합니다", Toast.LENGTH_LONG).show();
	    		}
	    		break;
	    		
	    	case R.id.booklist_searchbtn: //검색 
	    		
	    		EditText searchBookEt= (EditText) findViewById(R.id.booklist_searchedittext);
	    		String searchBook = searchBookEt.getText().toString();
	    		
	    		arItems = mBookMgr.selectListSearchByName("%"+searchBook+"%");
	    		//Toast.makeText(getBaseContext(), searchBook, Toast.LENGTH_LONG).show();
				adapter = new MainListAdapter(BookListActivity.this, arItems);
				grid.setAdapter(adapter);
				
				searchBookEt.setText("");
	    		break;
	    	}
	    }
	 
	 @Override
	    public void onBackPressed(){
				//메인 종료되기전 한번 물어보고 종료
				if(is_finish)							
					finish();
				else {
					Toast.makeText(getBaseContext(),"종료하시려면 이전버튼을 한번 더 누르세요.", 0).show();
					is_finish = true; //종료한다.
				}	
	    }
	 
	 
}//end of class




